﻿//using iTextSharp.text.pdf;
using Microsoft.Identity.Client;
using ToolCalendar.Model;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Policy;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using System.Windows.Forms;
using ToolCalendar.Helper;
using System.IO;
using System.Drawing;

namespace ToolCalendar
{
    public partial class MCalendar : Base
    {
        #region 属性

        /// <summary>
        /// 中国北京时区
        /// </summary>
        string timezone = "China Standard Time";

        /// <summary>
        /// 工作日报日历ID
        /// </summary>
        string ribao = "";

        /// <summary>
        /// 分类存储地址
        /// </summary>
        string categoryPath = $"{System.IO.Directory.GetCurrentDirectory()}/MicrosoftCategory.data";

        /// <summary>
        /// 分类Key存储地址
        /// </summary>
        string categoryKeyPath = $"{System.IO.Directory.GetCurrentDirectory()}/MicrosoftKeyCategory.data";
        #endregion

        public MCalendar()
        {
            InitializeComponent();
            base.SetDefaultLocation();


            DataBindTime(DateTime.Now.ToString("HH:00"));

            Login();
            DataBindCategory();
            GetLogAsync(DateTime.Now);
        }

        #region 添加事件

        private async void Btn_add_ClickAsync(object sender, EventArgs e)//添加事件
        {
            if (string.IsNullOrEmpty(ribao))
            {
                MessageBox.Show("请先加载日历分类!");
                return;
            }

            var url = $"https://graph.microsoft.com/beta/me/calendars/{ribao}/events";
            var isAllDay = false;
            var start = Picker_Start.Value.ToShortDateString() + " " + cob_start.Text;
            var end = Picker_End.Value.ToShortDateString() + " " + cob_end.Text;

            if (chb_all.Checked)
            {
                var time = DateTime.Now.ToShortDateString();
                isAllDay = true;
                end = start = DateTime.Now.ToShortDateString();
            }

            var obj = new
            {
                isAllDay = isAllDay,
                isReminderOn = false,//不提醒
                subject = txt_title.Text,
                body = new
                {
                    contentType = "text",
                    content = ""
                },
                start = new
                {
                    dateTime = start,
                    timeZone = timezone
                },
                end = new
                {
                    dateTime = end,
                    timeZone = timezone
                },
                location = new
                {
                    displayName = "中国辽宁省沈阳市"
                },
                allowNewTimeProposals = true,
                transactionId = Guid.NewGuid()
            };
            MicrosoftToken.HttpRequest(url, JsonConvert.SerializeObject(obj));

            //GetLogAsync(DateTime.Now);
            txt_title.Text = "";
            MessageBox.Show("添加事件成功!");
        }
        #endregion

        #region 获取事件列表 

        /// <summary>
        /// 登录
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private async void Login()
        {
            await MicrosoftToken.SetTokenAsync();
        }

        /// <summary>
        /// 获取事件
        /// </summary>
        /// <param name="time"></param>
        /// <returns></returns>
        private async void GetLogAsync(DateTime time)
        {
            GetCalendar(time);
        }

        /// <summary>
        /// 获取日历事件
        /// </summary>
        /// <param name="time"></param>
        private void GetCalendar(DateTime time)
        {
            if (string.IsNullOrEmpty(ribao))
            {
                MessageBox.Show("请先加载日历分类!");
                return;
            }

            var select = $"subject,body,bodyPreview,organizer,attendees,start,end,location";
            var filter = $"start/dateTime ge '{time.ToString("yyyy-MM-dd")}' and end/dateTime lt '{time.AddDays(1).ToString("yyyy-MM-dd")}'";
            var orderby = $"start/dateTime";
            var url = $"https://graph.microsoft.com/beta/me/calendars/{ribao}/events?$filter={filter}&$orderby={orderby}&$select={select}&$top=999";
            var res = MicrosoftToken.HttpRequest(url, "", "get");
            var list = JsonConvert.DeserializeObject<dynamic>(res).value;

            var events = new List<Model.CalenderModel>();
            foreach (var item in list)
            {
                events.Add(new Model.CalenderModel() { Title = item["subject"].ToString(), Start = Convert.ToDateTime(item["start"]["dateTime"].ToString()), End = Convert.ToDateTime(item["end"]["dateTime"].ToString()) });
            }

            var timeStr = DateTime.Now.ToString("HH:mm");
            var str = base.GetEevents(events, out timeStr);
            txt_Calendar.Text = str;
            cob_start.SelectedItem = timeStr;
        }
        #endregion

        #region 选择开始时间

        private void cob_start_SelectedIndexChanged(object sender, EventArgs e)
        {
            cob_end.SelectedItem = Convert.ToDateTime(Picker_Start.Value.ToShortDateString() + " " + cob_start.Text).AddHours(1).ToString("HH:mm");

            var flag = false;
            cob_end.Items.Clear();

            foreach (var item in time1)
            {
                if (item == cob_start.Text)
                {
                    flag = true;
                }
                if (flag)
                {
                    cob_end.Items.Add(item);
                }
            }
            cob_end.SelectedItem = Convert.ToDateTime("2018-08-16 " + cob_start.Text).AddHours(1).ToString("HH:mm");
        }
        #endregion

        #region 其它事件

        /// <summary>
        /// 时间 格式 HH:00
        /// </summary>
        /// <param name="dateTimeStr"></param>
        public void DataBindTime(string dateTimeStr)
        {
            cob_start.DataSource = time;
            cob_start.SelectedItem = dateTimeStr;
        }

        private void 月视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://outlook.live.com/calendar/0/view/month");
        }

        private void 天视图ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://outlook.live.com/calendar/0/view/day");
        }

        private void 查询事件ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            GetLogAsync(DateTime.Now);
        }

        private void monthCalendar1_DateChanged(object sender, DateRangeEventArgs e)
        {
            GetLogAsync(this.monthCalendar1.SelectionEnd);
        }
        private void 帮助wikiToolStripMenuItem_Click(object sender, EventArgs e)
        {
            System.Diagnostics.Process.Start("https://wiki.517cdn.com/index.php/日历工具集合");
        }
        #endregion


        #region 日历分类处理

        private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
        {
        }

        private void comboBox1_SelectedValueChanged(object sender, EventArgs e)
        {
            try
            {
                ribao = (comboBox1.SelectedItem as EventValue).id;
                GetLogAsync(this.monthCalendar1.SelectionEnd);
            }
            catch (Exception ex)
            {

            }
        }

        private void button1_Click(object sender, EventArgs e)//重新加载按钮
        {
            ReLoadCategory();
            DataBindCategory();
        }

        /// <summary>
        /// 重新加载分类
        /// </summary>
        private void ReLoadCategory()
        {
            var url = "https://graph.microsoft.com/beta/me/calendars";
            var str = MicrosoftToken.HttpRequest(url, "", "get");

            var list = JsonConvert.DeserializeObject<ToolCalendar.Model.EventModel>(str);
            var _list = list.value.Where(ex => ex.canEdit == true).ToList();

            //保存日历分类
            CommonLib.FileHelper.FileWrite(categoryPath, JsonConvert.SerializeObject(_list));
        }

        /// <summary>
        /// 加载分类下拉框
        /// </summary>
        private void DataBindCategory()
        {
            if (!File.Exists(categoryPath))
            {
                return;
            }

            var json = CommonLib.FileHelper.FileRead(categoryPath);
            var list = JsonConvert.DeserializeObject<List<EventValue>>(json);

            comboBox1.DataSource = list;
            comboBox1.DisplayMember = "name";
            comboBox1.SelectedIndex = -1;


            if (File.Exists(categoryKeyPath))
            {
                var _id = CommonLib.FileHelper.FileRead(categoryKeyPath);
                var entity = list.Where(ex => ex.id == _id).FirstOrDefault();
                comboBox1.SelectedItem = entity;
            }
        }
        #endregion

        #region 保存日历分类

        private void button2_Click(object sender, EventArgs e)//保存日历分类
        {
            try
            {
                //保存日历分类
                var value = comboBox1.SelectedValue;
                var id = (value as EventValue).id;

                CommonLib.FileHelper.FileWrite(categoryKeyPath, id);
                //CommonLib.FileHelper.FileWrite(categoryKeyPath, value);
            }
            catch (Exception)
            {
            }
        }
        #endregion
    }
}
